from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'name', 'price', 'description', 'image', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at']  # 设置这两个字段为只读
    
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        if instance.image:
            # 获取图片的相对路径
            image_path = instance.image.url
            # 确保只返回相对路径，不包含域名
            if image_path.startswith('http://') or image_path.startswith('https://'):
                # 分割URL，获取路径部分
                from urllib.parse import urlparse
                parsed_url = urlparse(image_path)
                image_path = parsed_url.path
            representation['image'] = image_path
        return representation
    